<template>
    <div class="article-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-duration="1000"
            :success-text="refreshingText">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error"
                error-text="请求失败，点击重新加载">
                <!-- <van-cell v-for="(item, index) in list" :key="index" :title="item.title" /> -->
                <ArticleItem v-for="(item, index) in list" :key="index" :title="item.title" :article="item">
                </ArticleItem>
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>
import { getArticles } from '../../../api/article';
import ArticleItem from '../../../components/article-item.vue';

export default {
    props: {
        channel_obj: {
            type: Object,
            required: true,
        }
    },
    data() {
        return {
            list: [],
            loading: false,
            finished: false,
            refreshing: false,
            timestamp: null || Date.now(),
            error: false,
            refreshingText: '刷新成功'
        };
    },
    methods: {
        async onLoad() {
            try {
                // 模拟人为错误
                // if (Math.random() > 0.5) {
                //     JSON.parse('sssss')
                // }
                const { data } = await getArticles({
                    channel_id: this.channel_obj.id,
                    timestamp: this.timestamp
                })
                const { results } = data.data
                this.list.push(...results)
                this.loading = false
                if (results.length) {
                    this.timestamp = data.data.pre_timestamp
                } else {
                    this.finished = true
                }
            } catch (err) {
                this.loading = false
                this.error = true;
            }
        },
        async onRefresh() {
            try {
                // 模拟人为错误
                // if (Math.random() > 0.5) {
                //     JSON.parse('sssss')
                // }
                const { data } = await getArticles({
                    channel_id: this.channel_obj.id,
                    timestamp: Date.now()
                })
                this.list.unshift(...data.data.results)
                this.refreshingText = `刷新成功了${data.data.results.length}条数据`
            } catch (err) {
                this.refreshingText = `刷新失败，请重试`
            }
            this.refreshing = false
        },
    },
    components: {
        ArticleItem,
    }
}
</script>

<style scoped lang="less">
.article-list {
    height: 79vh;
    overflow-y: auto;
}
</style>